<template>
	<view class="inviteCode">
		<view class="canvas" @click="saveCans()">

			<view v-if="needLongTapSaveImg==false"> <canvas
					:style="{ width: cansWidth + 'px', height: cansHeight + 'px' }" class="yui-share-blcok"
					canvas-id="firstCanvas"></canvas></view>
			<view v-show="needLongTapSaveImgs">
				<image :src="tempFilePaths" :style="{ width:cansWidth + 'px',height: cansHeight + 'px' }"
					class="yui-share-blcok"></image>
			</view>
			<view class="yui-share-button" @click="saveCans()">{{codetext}}</view>
		</view>
	</view>

</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				codeImg: '',
				username: '',
				codetext:'保存图片分享',
				needLongTapSaveImg: false,
				codeBg: '',
				codeUrl: '',
				cansWidth: 320, //海报宽度
				cansHeight: 596, //海报高度
				needLongTapSaveImgs: false,
				tempFilePaths: '',
				shareText:'关注店铺赢好礼',
				shareId: uni.getStorageSync('account'),
				userinfo:'',
				shopData:'',
			};
		},
		onShow() {
			this.tui.haslogin();
			if (this.tui.isLogin()) {
				this.shopData=this.tui.getShopData();
			}
		},
		onLoad(options) {
			this.tui.haslogin();
			this.initData();
		},
		onShareAppMessage() {
			this.userinfo = this.tui.getUserInfoData();
			
			return {
				title: this.shareText ? this.shareText : "关注店铺赢好礼",
				path: '/pageschild/shop/store?shareCode=' +this.userinfo.codes+'&shop_id='+this.shop_id,
				imageUrl: this.image
			}
		},
		computed: {
			...mapState(['account']),
		},
		methods: {
			initData() {
				let imgs = this.tui.getImgs();
				let token = this.tui.getToken();
				let datas = {
					token: token,
				};
				//#ifdef MP
				   let methodsUrl='merchantsWeachtStoreCode';
				//#endif
				// #ifndef MP
				    let methodsUrl='merchantsStoreCode';
				// #endif
				let result = this.tui.request('shop', 'post', datas, 1000, 1, '', methodsUrl);
				Promise.resolve(result).then((value) => {
					if (value.code == 200) {
						this.codeBg = value.data.qr_bg;
						this.codeImg = value.data.shop_collection_code;
						
						this.selseimg()
		
						//#ifdef H5
						// let ua = window.navigator.userAgent.toLowerCase()
						// if (ua.match(/MicroMessenger/i) == 'micromessenger') {
						// 	setTimeout(() => {
						// 		this.onShare();
						// 	}, 1000)
						// }
						// #endif
					} else {
						this.tui.toast(value.message);
					}
				})
				// }
			},
			selseimg() { //绘制海报
				let that = this;
				let names = 'firstCanvas';
				let rain = 2;
				uni.showLoading({
					title: '生成海报中'
				});
				const context = uni.createCanvasContext(names)
				//#ifdef MP
				uni.downloadFile({
					url: that.codeImg,
					success: function(res) {
				        that.codeImg=res.tempFilePath
					}
				})
				uni.downloadFile({
					url: that.shopData.shop_avatar,
					success: function(res) {
						that.shopData.shop_avatar = res.tempFilePath
					}
				})
				//#endif
				uni.downloadFile({
					url: this.codeBg,
					success: function(res) {
						// 图片加圆角
						that.handleBorderRect(context, 0, 0, that.cansWidth, that.cansHeight, 6 * rain);
						context.clip();
						context.drawImage(res.tempFilePath, 0, 0, that.cansWidth, that.cansHeight);
						
						setTimeout(function() { //定时器，海报方法不能立即执行，等页面渲染完成
							// that.handleBorderRect(context, 27*rain, 94*rain, 75*rain, 75*rain, 6*rain);
							context.drawImage(that.codeImg, 90, 220, 140, 140) //个人信息背景
							context.setFillStyle('#ffffff')
							context.setFontSize(12)
						    context.fillText(that.shopData.shop_name, 160, 480) //昵称
							context.fill()
							context.setFillStyle('#ffffff')
							context.setFontSize(11)
							context.fill()
							context.save()
							context.beginPath()
							context.drawImage(that.shopData.shop_avatar, 100, 450, 52, 52) //头像
							context.clip()
							context.restore()
							let tempRatio = 1.5;
							// #ifdef H5 || APP-PLUS
							tempRatio = 1;
							// #endif
							context.draw(true, () => {
								setTimeout(() => {
									uni.canvasToTempFilePath({
										x: 0,
										y: 0,
										width: that.cansWidth * tempRatio,
										height: that.cansHeight * tempRatio,
										destWidth: that.cansWidth * tempRatio *
											2,
										destHeight: that.cansHeight *
											tempRatio * 2,
										canvasId: names,
										success: (ress) => {
											that.tempFilePaths = ress
												.tempFilePath
											//#ifdef H5
											that.needLongTapSaveImg = true;
											that.needLongTapSaveImgs =
											true;
											//#endif
										}
									})
								})
							})
							uni.hideLoading();
						}, 100);
						uni.hideLoading();
						context.draw(true, function() {
							// uni.canvasToTempFilePath({
							// 	canvasId: 'activityCanvas',
							// 	fileType: 'png',
							// 	// destWidth: that.cansWidth,
							// 	// destHeight: that.cansHeight,
							// 	success: function(ress) {
							// 		// uni.hideLoading();
							// 		successFn && successFn(ress.tempFilePath);
							// 	}
							// })
						});
					}
				})

			},
			/**
			 * 图片圆角设置
			 * @param string x x轴位置
			 * @param string y y轴位置
			 * @param string w 图片宽
			 * @param string y 图片高
			 * @param string r 圆角值
			 */
			handleBorderRect(ctx, x, y, w, h, r) {
				ctx.beginPath();
				// 左上角
				ctx.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI);
				ctx.moveTo(x + r, y);
				ctx.lineTo(x + w - r, y);
				ctx.lineTo(x + w, y + r);
				// 右上角
				ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI);
				ctx.lineTo(x + w, y + h - r);
				ctx.lineTo(x + w - r, y + h);
				// 右下角
				ctx.arc(x + w - r, y + h - r, r, 0, 0.5 * Math.PI);
				ctx.lineTo(x + r, y + h);
				ctx.lineTo(x, y + h - r);
				// 左下角
				ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, Math.PI);
				ctx.lineTo(x, y + r);
				ctx.lineTo(x + r, y);

				ctx.fill();
				ctx.closePath();
			},

			saveCans() { //保存海报
				let that = this;
				
				let names = 'firstCanvas';
				//#ifdef H5
				this.tui.toast("请长按保存图片");
				return;
				//#endif
				//#ifdef APP-PLUS
				uni.showLoading({
					title: '保存海报中'
				});
				// #endif
				let tempRatio = 1.5;

				// #ifdef H5 || APP-PLUS

				tempRatio = 1;
				// #endif

				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: that.cansWidth * tempRatio,
					height: that.cansHeight * tempRatio,
					destWidth: that.cansWidth * tempRatio * 2,
					destHeight: that.cansHeight * tempRatio * 2,
					canvasId: names,
					success: function(res) {
						uni.hideLoading()
						/* 小程序 */
						// #ifdef MP-WEIXIN
										
						uni.getSetting({ //获取用户的当前设置
							success: (ress) => {
								if (ress.authSetting['scope.writePhotosAlbum']) { //验证用户是否授权可以访问相册
									that.aveImageToPhotosAlbum(res.tempFilePath);
								} else {
									uni.authorize({ //如果没有授权，向用户发起请求
										scope: 'scope.writePhotosAlbum',
										success: () => {
											that.aveImageToPhotosAlbum(res.tempFilePath);
										},
										fail: () => {
											// 提示
											uni.showToast({
												title: "请打开保存相册权限，再点击保存到手机",
												icon: "none",
												duration: 3000
											});
											setTimeout(() => {
												uni.openSetting({ //调起客户端小程序设置界面,让用户开启访问相册
													success: (
														res2) => {
														// console.log(res2.authSetting)
													}
												});
											}, 3000);
										}
									})
								}
							}
						})
						//#endif
						// #ifndef MP-WEIXIN
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: function(red) {
								uni.showToast({
									title: '保存相册成功'
								})
								that.imgsrc = res.tempFilePath
								if (e == 2) {
						
								}
							},
							fail(res) {
								if (res.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
									uni.showModal({
										title: '您需要授权相册权限',
										success(res) {
											if (res.confirm) {
												uni.openSetting({
													success(res) {
						
													},
													fail(res) {
														console.log(res)
													}
												})
											}
										}
									})
								}
							}
						});
						// #endif
					},
					fail(res) {
						uni.hideLoading()
					}
				}, this)
				
			},
			aveImageToPhotosAlbum(filePath) {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
						uni.saveImageToPhotosAlbum({ // 保存图片到系统相册
							filePath: filePath,
							success: function(res2) {
								uni.hideLoading();
								uni.showToast({
									title: '保存成功',
									icon: "none",
									duration: 5000
								})
							},
							fail: function(err) {
								uni.hideLoading();
								// console.log(err.errMsg);
							}
						})
			},
			share() {
				let names = 'firstCanvas';
				//#ifdef H5
				this.tui.toast("请用微信右上角分享");
				return;
				//#endif
				let tempRatio = 1.5;

				// #ifdef H5 || APP-PLUS
				tempRatio = 1;
				// #endif
   
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: that.cansWidth * tempRatio,
					height: that.cansHeight * tempRatio,
					destWidth: that.cansWidth * tempRatio * 2,
					destHeight: that.cansHeight * tempRatio * 2,
					canvasId: names,
					success: function(res) {
						// uni.hideLoading()
						uni.shareWithSystem({
							provider: "weixin",
							// scene: "WXSceneSession",
							type: 2,
							imageUrl: res.tempFilePath,
							success: function(res) {
								uni.showToast({
									title: JSON.stringify(err),
									duration: 2000,
									icon: 'none'
								});
							},
							fail: function(err) {

								console.log("fail:" + JSON.stringify(err));
							}
						});
					},
					fail(res) {
						uni.hideLoading()
					}
				}, this)

			},
			onShare() {
				//#ifdef APP-PLUS
				plus.share.sendWithSystem({
						content: '商城',
						href: ''
					},
					function() {
						console.log('分享成功');
					},
					function(e) {
						console.log('分享失败：' + JSON.stringify(e));
					}
				);
				//#endif
				// #ifdef H5
				this.userinfo = this.tui.getUserInfoData();
				let urls = this.tui.getUrl() + 'pageschild/shop/store?shareCode=' +this.userinfo.codes+'&shop_id='+this.shop_id;
				var jweixin = require('jweixin-module')
				let token = this.tui.getToken();
				let obj = {
					token: token,
					url: encodeURIComponent(window.location.href.split('#')[0]),
				}
				// console.log(window.location.href.split('#'))
				let orders = this.tui.request('user', 'post', obj, 1000, 1, '', 'wxShare');
				let that = this;
				Promise.resolve(orders).then((value) => {
					if (value.code == 200) {

						jweixin.config({
							debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。  
							appId: value.data.appId, // 必填，公众号的唯一标识  
							timestamp: value.data.timestamp, // 必填，生成签名的时间戳  
							nonceStr: value.data.nonceStr, // 必填，生成签名的随机串  
							signature: value.data.signature, // 必填，签名，见附录1  
							surl: value.data.url, //自己添加的，debug为true的时候可以网页打印出对应的URL是否正确  
							jsApiList: ["updateAppMessageShareData", "updateTimelineShareData"],
						});
						jweixin.ready(function() {
							//自定义“分享给朋友”及“分享到QQ”按钮的分享内容（1.4.0）

							let descs = '关注店铺赢好礼';
							jweixin.updateAppMessageShareData({
								title: '关注店铺赢好礼',
								desc: descs, // 分享描述
								link: urls,
								imgUrl: that.codeBg,
								success: function(res) {

								},

							});
							//自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容（1.4.0）  
							jweixin.updateTimelineShareData({
								title: '关注店铺赢好礼',
								link: urls,
								imgUrl: that.codeBg,
								success: function() {
									// 用户确认分享后执行的回调函数  
								},
							});

						});
					} else {

						this.showToast(value.message)

					}
				})

				// #endif
			},
		}
	}
</script>

<style lang="scss">
	page {
		height: 100vh;
	}

	.share_footer {
		width: 100%;
		position: fixed;
		color: #fff;
		bottom: 20rpx;
		height: 140rpx;
		padding: 30rpx 0;
		z-index: 100000;


	}

	.yui-face {

		width: 100%;
		position: absolute;
		top: 48%;
	}

	.yui-share-blcok {
		border-radius: 40rpx;
		width: 100%;
		margin: 0 auto;
		padding: 0rpx;

	}
    .yui-share-button{
		
		position: relative;
		width:466rpx;
		border-radius: 40rpx;
		color:#fff;
		padding:22rpx 20rpx;
		font-size: 28rpx;
		margin:0 auto;
		margin-top: 40rpx;
		font-weight: bold;
		box-shadow: 4rpx 10rpx 20rpx rgba(0, 0, 0, 0.1);
		background-image: linear-gradient(100deg, #fdb31f, #fdad0b);
	}
	.yui-share-blcok img {
		border-radius: 40rpx;
	}

	.yui-face-img {
		border-radius: 50%;
		width: 100rpx;
		flex-shrink: 0;
		height: 100rpx !important;

		// height: 20%;
	}

	.inviteCode {
		position: relative;
		width: 100% !important;
		min-height: 100vh;
		text-align: center;

		// height: 100%;
		// background-image: linear-gradient(to bottom, #79b3fd, #79b3fd);
		background:#fff;
		background-repeat: no-repeat;
		// background-size: 100%;

	}

	.share_box {
		text-align: center;
		justify-content: space-between;
		font-size: 22rpx;
		line-height: 34rpx;
		color: #353535;
		padding: 24rpx 20rpx;
		display: flex;
		margin: 20rpx;
		border-radius: 20rpx;
		background: #e5ab4c;
	}

	.canvas {
		padding-top: 60rpx;
	}

	uni-image {
		width: 500px;
	}

	.share_box_span {
		display: block;
		width: 33%;
	}

	.share_box_text {
		display: block;
		color: #fff;
		text-align: center;
	}

	.share_icon {
		width: 60rpx;
	}
</style>
